Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

LINQ in C#



LINQ (Language Integrated Query) is one of the most powerful features in C#. It allows developers to write queries directly within the C# programming language, enabling them to work with various data sources, such as collections, databases, XML, and more in a declarative way.

Key Features of LINQ:

  • Declarative Syntax: Write code that describes what you want, rather than how to achieve it.

  • Strong Typing: Queries are strongly typed, and any errors are caught at compile time.

  • IntelliSense Support: Provides full IntelliSense support in Visual Studio, making it easier to write and understand queries.

  • Language Integration: Integrated into the C# language, making it a first-class citizen.

  • Data Consistency: Provides a consistent way to query various data sources, using the same syntax.

Core Components:

  1. LINQ to Objects: Used to query in-memory collections, like arrays and lists.

  2. LINQ to SQL: Used to query SQL databases.

  3. LINQ to XML: Used to query and work with XML data.

  4. LINQ to Entities: Used to query Entity Framework data models.

Basic LINQ Query Structure:

LINQ queries consist of three main parts:

  1. Data Source: The collection or data source you want to query.

  2. Query Creation: The query expression that specifies what data to retrieve.

  3. Query Execution: Executing the query to get the results.

Examples:

1. LINQ to Objects:

Here's a simple example of querying an array of integers:

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// LINQ Query to get even numbers
var evenNumbers = from n in numbers
                  where n % 2 == 0
                  select n;

Console.WriteLine("Even numbers:");
foreach (var num in evenNumbers)
{
    Console.WriteLine(num);
}

2. LINQ to SQL:

Let' assume we have a database context and want to query it:

csharp
using (var context = new MyDbContext())
{
    var students = from s in context.Students
                   where s.Grade == "A"
                   select s;

    Console.WriteLine("Students with grade A:");
    foreach (var student in students)
    {
        Console.WriteLine(student.Name);
    }
}

3. LINQ with Method Syntax:

LINQ queries can also be written using method syntax, which is similar to calling extension methods:

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// LINQ Query to get even numbers using method syntax
var evenNumbers = numbers.Where(n => n % 2 == 0).Select(n => n);

Console.WriteLine("Even numbers (method syntax):");
foreach (var num in evenNumbers)
{
    Console.WriteLine(num);
}

Common LINQ Methods:

  • Where: Filters elements based on a predicate.

  • Select: Projects each element into a new form.

  • OrderBy: Sorts elements in ascending order.

  • OrderByDescending: Sorts elements in descending order.

  • GroupBy: Groups elements that share a common attribute.

  • Join: Joins two collections based on matching keys.

  • Sum, Min, Max, Average: Calculates aggregate values.

  • Take, Skip: Retrieves a subset of the elements.

Example with Multiple Methods:

csharp
var result = numbers
    .Where(n => n % 2 == 0)
    .OrderByDescending(n => n)
    .Take(3)
    .Select(n => new { Number = n, IsEven = true });

Console.WriteLine("Processed numbers:");
foreach (var item in result)
{
    Console.WriteLine($"Number: {item.Number}, IsEven: {item.IsEven}");
}

Benefits of Using LINQ:

  • Conciseness: Write complex queries in fewer lines of code.

  • Readability: Queries are easier to read and understand.

  • Maintainability: Makes code easier to maintain and modify.

  • Consistency: Use a consistent querying model across different data sources.

LINQ is an incredibly versatile tool in C# that brings the power of queries into the language itself, making data manipulation tasks more efficient and enjoyable. If you have specific scenarios or questions related to LINQ, feel free to ask!




All rights reserved | Privacy Policy | Sitemap